package com.employment.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.employment.dao.ChatTemplateMapper;
import com.employment.entity.ChatTemplate;
import com.employment.service.ChatTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.employment.entity.table.ChatTemplateTableDef.CHAT_TEMPLATE;

/**
 * 常用回复模板服务实现
 * 
 * @author employment
 * @since 2024-01-01
 */
@Slf4j
@Service
public class ChatTemplateServiceImpl implements ChatTemplateService {
    
    @Autowired
    private ChatTemplateMapper templateMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatTemplate createTemplate(Long userId, String title, String content, String category) {
        log.info("创建常用回复模板，用户ID：{}，标题：{}", userId, title);
        
        ChatTemplate template = new ChatTemplate();
        template.setUserId(userId);
        template.setTitle(title);
        template.setContent(content);
        template.setCategory(category);
        template.setUsageCount(0);
        
        templateMapper.insert(template);
        
        log.info("常用回复模板创建成功，模板ID：{}", template.getTemplateId());
        return template;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatTemplate updateTemplate(Long templateId, Long userId, String title, String content, String category) {
        log.info("更新常用回复模板，模板ID：{}，用户ID：{}", templateId, userId);
        
        // 检查模板是否存在且属于当前用户
        ChatTemplate template = templateMapper.selectOneById(templateId);
        if (template == null || !template.getUserId().equals(userId)) {
            throw new RuntimeException("模板不存在或无权限修改");
        }
        
        template.setTitle(title);
        template.setContent(content);
        template.setCategory(category);
        
        templateMapper.update(template);
        
        log.info("常用回复模板更新成功");
        return template;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTemplate(Long templateId, Long userId) {
        log.info("删除常用回复模板，模板ID：{}，用户ID：{}", templateId, userId);
        
        // 检查模板是否存在且属于当前用户
        ChatTemplate template = templateMapper.selectOneById(templateId);
        if (template == null || !template.getUserId().equals(userId)) {
            throw new RuntimeException("模板不存在或无权限删除");
        }
        
        templateMapper.deleteById(templateId);
        
        log.info("常用回复模板删除成功");
    }
    
    @Override
    public List<ChatTemplate> getUserTemplates(Long userId, String category) {
        log.info("获取用户常用回复模板，用户ID：{}，分类：{}", userId, category);
        
        QueryWrapper queryWrapper = QueryWrapper.create().from(CHAT_TEMPLATE)
                .where(CHAT_TEMPLATE.USER_ID.eq(userId));
        
        if (StringUtils.hasText(category)) {
            queryWrapper.and(CHAT_TEMPLATE.CATEGORY.eq(category));
        }
        
        queryWrapper.orderBy(CHAT_TEMPLATE.USAGE_COUNT.desc(), CHAT_TEMPLATE.UPDATED_AT.desc());
        
        List<ChatTemplate> templates = templateMapper.selectListByQuery(queryWrapper);
        
        log.info("获取到{}个常用回复模板", templates.size());
        return templates;
    }
    
    @Override
    public List<ChatTemplate> searchTemplates(Long userId, String keyword) {
        log.info("搜索常用回复模板，用户ID：{}，关键词：{}", userId, keyword);

        QueryWrapper queryWrapper = QueryWrapper.create().from(CHAT_TEMPLATE)
                .where(CHAT_TEMPLATE.USER_ID.eq(userId));
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(CHAT_TEMPLATE.TITLE.like(keyword)
                    .or(CHAT_TEMPLATE.CONTENT.like(keyword)));
        }
        
        queryWrapper.orderBy(CHAT_TEMPLATE.USAGE_COUNT.desc(), CHAT_TEMPLATE.UPDATED_AT.desc());
        
        List<ChatTemplate> templates = templateMapper.selectListByQuery(queryWrapper);
        
        log.info("搜索到{}个常用回复模板", templates.size());
        return templates;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void incrementUsageCount(Long templateId, Long userId) {
        log.info("增加模板使用次数，模板ID：{}，用户ID：{}", templateId, userId);
        
        // 检查模板是否存在且属于当前用户
        ChatTemplate template = templateMapper.selectOneById(templateId);
        if (template == null || !template.getUserId().equals(userId)) {
            throw new RuntimeException("模板不存在或无权限操作");
        }
        
        template.setUsageCount(template.getUsageCount() + 1);
        
        templateMapper.update(template);
        
        log.info("模板使用次数已增加");
    }
    
    @Override
    public List<ChatTemplate> getFrequentlyUsedTemplates(Long userId, Integer limit) {
        log.info("获取常用模板，用户ID：{}，限制数量：{}", userId, limit);
        
        QueryWrapper queryWrapper = QueryWrapper.create().from(CHAT_TEMPLATE)
                .where(CHAT_TEMPLATE.USER_ID.eq(userId))
                .and(CHAT_TEMPLATE.USAGE_COUNT.gt(0))
                .orderBy(CHAT_TEMPLATE.USAGE_COUNT.desc());
        
        if (limit != null && limit > 0) {
            queryWrapper.limit(limit);
        }
        
        List<ChatTemplate> templates = templateMapper.selectListByQuery(queryWrapper);
        
        log.info("获取到{}个常用模板", templates.size());
        return templates;
    }
}